
import axios from 'axios';
import dayjs from 'dayjs';
import Cookies from 'js-cookie';
axios.interceptors.response.use(function (res) {
    return res.data;
}, function (err) {
    return err.response;
});

// 服务器API 
const URL = {
    BASE: "http://" + window.location.host.replaceAll(":8080", "") + ":8888",
    API_TAB_LIST: "/tab/list",
    API_TAB_PUSH: "/tab/push",
    API_PARENT_QUERY: "/list/parent",
    API_STATUS_OPTIONS: "/list/parent/sel_options",
    API_UPLOAD_RICH_IMAGHE: "/list/children/img_push",
    API_UPLOAD_RICH_CONTENT: "/list/children/content_push",
    API_USER_SIGN: "/user/register",
    API_USER_INFO: "/user/info",
    API_USER_LIST: "/user/all_list",
    API_USER_LOGINL: "/user/login",
    API_USER_LOGOUT: "/user/logout",
    API_USER_SEARCH: "/user/search",
    API_USER_INFO_PWD: "/user/modify/password",
    API_USER_INFO_MODIFY: "/user/info_modify",
    API_USER_SET_STATUS: "/user/set_status",
    API_UPLOAD_FILE_AVG: "/user/avg_modify",
    API_TAB_RENAME: "/tab/rename",
    API_TAB_DEL: "/tab/del",
    API_PARENT_PUSH: "/list/parent/push",
    API_TYPE_OPTIONS: "/list/children/work_type",
    API_CHILD_PUSH: "/list/children/push",
    CHILD_DETAIL: "/list/children/detail",
    API_SYSTEM: "/sys/info",
    API_CONFIG_TABLE: "/config/table"
}
/**
 * 删除object里面不需要的属性
 * @param {*} arr 对象
 * @param  {...any} args 属性多选
 * @returns 删除后的
 */
function remove_prop(arr, ...args) {
    for (const a in args) {
        delete arr[args[a]];
    }
    return arr;
}
/**
 * 字符串判空
 */
const str_utils = {
    is_empty(str) {
        if (!str) {
            return true;
        }
        else if (typeof str === 'string') {
            return str.trim().length === 0;
        }
    },
    not_empty(str) {
        return !this.is_empty(str);
    }
}
/**
 * @obj node
 * @return any
 */
function key_to_val(obj, val) {
    if (!obj || Object.keys(obj).length === 0) {
        return undefined;
    }
    return obj[val];
}

/**
 * 
 * @param {*} config { url?:srting,type:json|text ,data:object}
 * @returns 
 */
/**
 * 时间格式化
 * @param 
 * @returns 
 */

const TimeFormatter = function (time = null) {
    let date = time ? new Date(time) : new Date();
    let year = date.getFullYear();
    let month = (date.getMonth() + 1);
    month = month >= 10 ? month : '0' + month;
    let day = date.getDate();
    day = day >= 10 ? day : '0' + day;
    let hours = date.getHours();
    hours = hours >= 10 ? hours : '0' + hours;
    let min = date.getMinutes();
    min = min >= 10 ? min : '0' + min;
    let sec = date.getSeconds();
    sec = sec >= 10 ? sec : '0' + sec;
    return {
        get_full(y = ' ', M = ' ', d = ' ', h = ':', m = ':', s = '') {
            console.log(hours)
            return year + y + month + M + day + d + hours + h + min + m + sec + s
        },
        get_date(y = ' ', M = ' ', d = ' ') {
            return year + y + month + M + day + d;
        },
        get_time(h = ':', m = ':', s = '') {
            return hours + h + min + m + sec + s;
        }
    }
}
/**
 * 时间对比工具
 * @before 之前
 * @after 之后 如果为空就以当前时间为准
 * @returns bool
 */
const TimeCompareWidth = function (before, after) {
    if (!before) {
        return {
            is_before() {
                return undefined
            },
            is_after() {
                return undefined
            }, is_equal() {
                return undefined
            }
        }
    };
    let _before = typeof before === 'string' ? new Date(before) : before;
    let _after = typeof after === 'string' ? new Date(before) : after ? after : new Date();
    return {
        is_before() {
            return dayjs(_before).isBefore(_after);
        },
        is_after() {
            return dayjs(_before).isAfter(_after);
        },
        is_equal() {
            return dayjs(_before).isSame(_after);
        }
    }
}
/**
 * 判断json object 不为空
 */
function obj_empty(obj) {
    if (!is_object(obj)) { return true };
    return Object.keys(obj).length === 0;
}

/**
 * 判断参数是object
 * @param obj 输入参数
 * @returns bool
 */
function is_object(obj) {
    if (null === obj || typeof obj !== 'object') {
        return null;
    }
    return Object.keys(obj).length >= 0;
}
/**
 * 检测json 对象里面有空值与否
 * @param obj {data} 
 * @param args 指定keys 未定参
 * @returns bool
 */
function jsonHasEmpty(obj, ...args) {
    if (!is_object(obj)) {
        return false;
    }
    else if (args.length <= 0) {
        return true;
    }
    else {
        let pass = true;
        for (const k of args) {
            let val = obj[k];
            if (typeof val === 'string') {
                if (str_utils.is_empty(val)) {
                    pass = false;
                    break;
                }
            } else if (typeof val === 'object') {
                pass = val !== null;
                break;
            } else if (typeof val === 'function') {
                pass = false;
                break;
            }
        }
        return pass;
    }
}
/**
 * 正则验证
 * @params str 传入字符串
 * @return obj{Account() 参数b：bool false set True 返回当前字符串,反之返回bool }
 */
// 用户名
const REG_USER = /^[a-zA-Z0-9]{7,12}$/ // 数字和字母组合 8~12位
// 密码
const REG_PWD = /^[A-Z][a-zA-Z0-9]{7,10}$/ // 大写字母开头 8~10位
// 特殊字符 
const REG_CHAR = /[`~!@#$%^&*()+=|{}':;',\[\].<>?~！@#￥%……&*（）——+|{}【】‘；：”“'。，、？]$/;
// 过滤器
const RegRules = function (str) {
    return {
        Password(b = false) {
            const res = REG_PWD.test(str);
            return this.__(b, res);
        },
        Account(b = false) {
            const res = REG_USER.test(str);
            return this.__(b, res);
        },
        Char(b = false) {
            const res = REG_CHAR.test(str);
            return this.__(b, res);
        },
        __(b, res) {
            if (res) {
                return b ? str : res;
            } else if (str_utils.is_empty(str)) {
                return false;
            } else {
                return res;
            }
        }
    }
}
/**
 * 网络请求
 * @config {url,data,type=json,params:object}
 */
const get = function (config) {
    if (!config.url) {
        console.error("非法地址", config.url);
        return undefined;
    }
    return axios({
        method: "GET",
        url: config.url || null,
        params: key_to_val(config, "params")
    });
}
/**
 * 网络请求
 * @config {url,data,type=json,params:object}
 */
const post = function (config) {
    if (!config.url) {
        console.error("非法地址", config.url);
        return undefined;
    }
    let headers;
    if (config && config.headers) {
        headers = {
            'Content-Type': 'application/json',
            ...config.headers
        }
    } else {
        headers = {
            'Content-Type': 'application/json',
        }
    }
    return axios({
        method: "POST",
        headers,
        url: config.url || null,
        data: key_to_val(config, "data")
    });
}

/**
 * 网络请求
 * @config {url,formData,type=json,params:object}
 */
const post_form = function (config) {
    if (!config.url) {
        console.error("非法地址", config.url);
        return;
    } else {
        let headers = {
            "Content-Type": "multipart/form-data"
        };
        return axios.post(config.url, config.formData, {
            headers
        });
    }
}
/**
 * 上传文件
 *  @param config{
 *  data fromdata
 *  fileList:[] 数组
 * }
 */
const upload = function (config) {
    if (!config.url) {
        console.error("非法地址", config.url);
        return undefined;
    }
    const formData = new FormData(); // 表单数据
    const list = config.fileList || [], _data = config.data;
    if (list && list.length > 0) {
        for (let i = 0; i < list.length; i++) {
            const file = list[i];
            formData.append('file_list', file);
        }
    }
    if (_data) {
        let keys = Object.keys(_data);
        for (let key = 0; key < keys.length; key++) {
            const _key = keys[key];
            const val = _data[_key];
            formData.append(_key, val);
        }
    }
    return axios.post(config.url, formData, {
        headers: {
            'Content-Type': 'multipart/form-data',
        }
    });
}
/*
    获取用户信息
*/
const user_info = function () {
    let token = Cookies.get("token");
    if (str_utils.not_empty(token)) {
        return post({
            url: URL.BASE + URL.API_USER_INFO,
            headers: {
                "Content-Type": "application/json"
            },
            data: {
                token,
            }
        });
    } else {
        return Promise.reject('no login');
    }
}
/**
 * 优先级颜色参数
 */
const get_theme_color = function (val) {
    if (val !== isNaN && typeof val === 'number') {
        switch (val) {
            case -1:
                return "#296dff";
            case 0:
                return "#FFA500";
            case 1:
                return "#FF7F50";
            case 2:
                return "#FF6347";
            case 3:
                return "#FF0000";
            default:
                return "#FFC0CB";
        }
    }
    else {
        return "white";
    }
}

// 文件配置
const file_config = {
    __avg_accept: ['jpg', 'jepg', 'png', 'webp', 'gif'],
    avg_to_str() {
        let str = (this.__avg_accept.join(',').replaceAll(',', ',.'))
        return '.' + str;
    },
    match(str) {
        if (str_utils.not_empty(str)) {
            return this.__avg_accept.indexOf(str) !== -1;
        } return false;
    },
    get_sufix(file_name) {
        return file_name.substring(file_name.lastIndexOf('.') + 1);
    },
    full_name_match(str) {
        if (str_utils.not_empty(str)) {
            let suf = this.get_sufix(str);
            return this.__avg_accept.indexOf(suf) !== -1;
        } return false;
    },
    limit_size(file, max_size) { // kb
        if (file && file.type) {
            return (file.size / 1024) >= max_size
        }
        return false;
    }
}
/**
 * 数值过度
 * @param target 
 * @param end 
 * @param time 时间
 */
function counter(start, end, time = 0, run_callback) {
    let _start = 0;
    if (start === end) {
        return
    }
    else if (typeof run_callback === 'function') {
        run_callback(end);
    }
    let u = true; // true ++ false --
    if (time < 0) {
        return
    }
    else if (time === 0) {
        if (typeof run_callback === 'function') {
            run_callback(end);
        }
    } else {
        _start = start;
        u = start > end;
        function __() {
            if (u) {
                _start -= (Math.abs(time) ** 2);
                if (_start <= end) {
                    return;
                }
            } else {
                _start += (Math.abs(time) ** 2);
                if (_start >= end) {
                    return;
                }
            }
            if (typeof run_callback === 'function') {
                run_callback(_start);
            }
            window.requestAnimationFrame(() => __());
        }
        __();
    }
}
// 优先级选择框
const priority_options = [
    {
        value: -1,
        label: "待设置",
    },
    {
        value: 0,
        label: "低",
    },
    {
        value: 1,
        label: "中",
    },
    {
        value: 2,
        label: "高",
    },
    {
        value: 3,
        label: "紧急",
    },
];
/*
* name 查找数组中的object 的值获取对象
* arr 查找的数组
* key 对象中的查找Key
* value 对应的值
* return {***}
*/

function find_object_val(arr, key, value) {
    let res = {};
    if (!key || str_utils.is_empty(key) || !value) { return res; }
    if (arr && arr.length && arr.length > 0) {
        Array.from(arr).forEach((val, index) => {
            if (val[key] === value) {
                res = val;
                res.index = index;
                return;
            }
        })
    }
    return res;
}
const c = find_object_val([{ val: 1, label: '第一个' }, { val: 2, label: '第二个' }], "val", 1);

/**
 * @name 延迟执行函数
 * @param {*} call 不定参数
 * @returns {
 *  wait 等待time s 后执行call
 *  finish 直接完成 手动调用
 *  stop 中断执行
 *  链式调用
 * }
 */
const Thread = function (...call) {
    if (!call) {
        return null;
    }
    let timer = null;
    let args = call;
    let i = 0;
    return {
        wait(time = 0) {
            let len = args.length;
            timer = setTimeout(() => {
                while (i < len) {
                    let fun = args[i];
                    if (fun && typeof fun === 'function') {
                        args[i]();
                    }
                    args.slice(i, 1);
                    i += 1; //推出
                }
                i = 0;
            }, time);
            return this;
        },
        finish() {
            this.stop();
            i = 0;
            if (args.length > 0) {
                while (i < args.length) {
                    args[i]();
                    args.splice(i, 1); //推出
                    i++;
                }
                i = 0;
            }
            return this;
        },
        stop() {
            clearTimeout(timer);
            return this;
        },
        done() {

        }
    }
}

export {
    Thread,
    find_object_val,
    priority_options,
    counter,
    upload,
    file_config,
    get_theme_color,
    remove_prop,
    str_utils,
    get,
    post,
    URL,
    TimeFormatter,
    RegRules,
    obj_empty,
    user_info,
    TimeCompareWidth,
    REG_CHAR,
    is_object,
    jsonHasEmpty,
    post_form
}